package com.yunze.apiCommon.upstreamAPI.XunZhong;

import com.alibaba.fastjson.JSON;
import com.yunze.apiCommon.utils.HttpUtil;
import org.apache.commons.codec.binary.Base64;



import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 讯众物联 API
 * @author: zhangfeng
 * @version: v1.0
 * @date:2023/02/13
 */
public class XunZhongApi {

    // 账户设置 -> API 信息 中可看到 API_ID 和 API_SECRET
    public static  String API_ID = "";
    public static  String API_SECRET = "";

    protected  static String server_Ip = "";

    //构造赋值
    public XunZhongApi(Map<String, Object> init_map){


        API_ID = init_map.get("cd_username").toString();
        API_SECRET = init_map.get("cd_pwd").toString();
        server_Ip = init_map.get("cd_key").toString()+"/api/customer/v1";
    }


    public static void main(String[] args) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cd_username", "2266198810847753");
        map.put("cd_pwd", "p2qBx3tJDO1z6ZSw2T49QNBlQjLBF5Yv");
        map.put("cd_key", "https://iot.commchina.net");


        XunZhongApi Qy = new XunZhongApi(map);
        System.out.println(Qy.get_sim_card_detail("898602B5092190145358"));




    }

    /**
     * 批量卡号信息查询 (查询卡在系统中的详情信息（最多100张，若超过100张，只取前100张处理）。)
     * @param iccid
     * @return
     */
    public String get_sim_card_detail(String iccid){
        String url = server_Ip+"/sim_cards/get_sim_card_detail";

        // 参数初始化
        String currentTime = String.valueOf(System.currentTimeMillis() / 1000);
        Map<String, Object> params = new HashMap<>();
        params.put("api_id", API_ID);
        params.put("timestamp", currentTime);
        params.put("iccids", iccid);
        // 参数按 key 排序
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String sign = "";
        for (String key : keys) {
            String value = (String) params.get(key);
            if (!sign.equals("")) {
                sign += "&";
            }
            sign += (key + "=" + value);
        }
        // ⽣成 sign
        sign += API_SECRET;
        // 添加加密的 sign
        String signStr = SHA256(encode(sign.getBytes()));
        params.put("sign", signStr);
        String data = JSON.toJSONString(params);
        System.out.println(data);
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        String result = null;
        try {
            result = HttpUtil.doPost(url,params);
        }catch (Exception e){
            System.err.println("XunZhongApi.java  get_sim_card_detail 异常 "+e.getMessage());
        }
        return  result;
    }








    // Base 64 加密
    public static String encode(final byte[] bytes) {
        return new String(Base64.encodeBase64(bytes));
    }

    // SHA 256 加密
    public String SHA256(final String strText) {
        return SHA(strText, "SHA-256");
    }

    private String SHA(final String strText, final String strType) {
        // 返回值
        String strResult = null;
        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密开始
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
                // 传⼊要加密的字符串
                messageDigest.update(strText.getBytes());
                // 得到 byte 结果
                byte byteBuffer[] = messageDigest.digest();
                // 將 byte 转换 string
                StringBuffer strHexString = new StringBuffer();
                // 遍历 byte buffer
                for (int i = 0; i < byteBuffer.length; i++) {
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                strResult = strHexString.toString();
            }
            // 得到返回結果
            catch(NoSuchAlgorithmException e){
                e.printStackTrace();
            }
        }
        return strResult;
    }
}
